package com.eco.fanliapp.controller.exapi;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.eco.fanliapp.common.response.ServerResponse;
import com.eco.fanliapp.entity.*;
import com.eco.fanliapp.service.*;
import com.eco.fanliapp.utils.DateUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * @date 2019-10-14
 * 限时秒杀对外接口
 */
@RestController
@RequestMapping("/sy/seckill")
public class OpenDoorSeckillController {


    @Autowired
    private ISyTimePeriodService iSyTimePeriodService;
    @Autowired
    private ISyModuleService iSyModuleService;

    @Autowired
    private ISyTimePeriodGoodsService iSyTimePeriodGoodsService;

    @Autowired
    private ISyTimePeriodAppointmentService iSyTimePeriodAppointmentService;

    @Autowired
    private ITaoBaoService iTaoBaoService;

    /**
     * 秒杀首页列表
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping(value = "homePageList")
    public ServerResponse homePageList(@RequestParam(defaultValue = "0") Integer pageNum, @RequestParam(defaultValue = "3") Integer pageSize) {

        JSONObject jsonObject = new JSONObject();
        SyModule syModule = iSyModuleService.getById(7);//
        if (!syModule.getEnable()) return ServerResponse.createBySuccessCodeMessage(201, "查询为空");
        List<SyTimePeriod> syTimePeriodList = iSyTimePeriodService.syTimePeriodList(pageNum, pageSize, new Date().getHours() - 1, 0);
        if (syTimePeriodList.size() < 3) {
            syTimePeriodList = iSyTimePeriodService.syTimePeriodList(pageNum, pageSize, new Date().getHours() - 1, 1);
            Collections.reverse(syTimePeriodList);
        }
        jsonObject.put("syTimePeriodList", syTimePeriodList);
        long sysTime = System.currentTimeMillis();
        long countDown = sysTime;
        String s = DateUtils.date2Str(new Date(), DateUtils.DATE_FORMAT_YYYYMMDD);

        for (SyTimePeriod syTimePeriod : syTimePeriodList) {
            String startTimeStr = s + " " + syTimePeriod.getPeriodTime() + ":00";
            long startTime = DateUtils.datestr2Date(startTimeStr, DateUtils.DATE_FORMAT_YYYYMMDDHHMMSS).getTime();
            if (startTime > sysTime) {
                countDown = startTime - sysTime;
                break;
            }
        }
        jsonObject.put("countDown", countDown);
        return ServerResponse.createBySuccess("查询成功", jsonObject);
    }

    /**
     * 秒杀时间段列表
     *
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping(value = "timeList")
    public ServerResponse list(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "20") Integer pageSize) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("enable", 1);
        queryWrapper.eq("deleted", 0);
        Page<SyTimePeriod> page = new Page<>(pageNum, pageSize);
        IPage iPage = iSyTimePeriodService.page(page, queryWrapper);
        List<SyTimePeriod> syTimePeriodList = iPage.getRecords();
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("iPage", iPage);
        int hours = new Date().getHours();
        for (SyTimePeriod syTimePeriod : syTimePeriodList) {
            String periodTime = syTimePeriod.getPeriodTime();
            String[] split = periodTime.split(":");
            Integer integer = Integer.valueOf(split[0]);
            if (hours > integer) {
                syTimePeriod.setStatus(1);//已开抢
            }
            if (hours == integer || hours == integer + 1) {
                syTimePeriod.setStatus(2);//抢购中
            }
        }
        return ServerResponse.createBySuccess("查询成功", iPage);
    }


    @GetMapping(value = "timeGoodsList")
    public ServerResponse list(@RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize, Integer tableId, @RequestParam(defaultValue = "0") Integer hotCake, @RequestParam(defaultValue = "") String time) {
        if (tableId == null) {
            return ServerResponse.createByErrorMessage("参数有误");
        }
        String strDate = "";
        if (time == null || "".equals(time)) {
            strDate = DateUtils.date2Str(new Date(), DateUtils.DATE_FORMAT_YYYYMMDD);
        } else {
            strDate = time;
        }
        SyTimePeriod syTimePeriod = iSyTimePeriodService.getById(tableId);
        if (StringUtils.isEmpty(syTimePeriod)) return ServerResponse.createByErrorMessage("参数有误");
        QueryWrapper queryWrapper = new QueryWrapper();
        String[] split = syTimePeriod.getPeriodTime().split(":");
        int hours = new Date().getHours();
//        if(hours < Integer.valueOf(split[0]) && hotCake == 0){
//        }else if(hours < Integer.valueOf(split[0]) && hotCake == 1){
//            queryWrapper.eq("hot_cake", -1);
//        }else{
//            queryWrapper.eq("hot_cake", hotCake);
//        }

        if (hotCake == -1) {
            //-1查询所有 0不查爆款 1只查爆款
        } else {
            queryWrapper.eq("hot_cake", hotCake);
        }

        queryWrapper.eq("enable", 1);
        queryWrapper.eq("deleted", 0);
        queryWrapper.eq("period_id", tableId);
        queryWrapper.orderByDesc("hot_cake");
        queryWrapper.orderByAsc("top_serial_num");
        queryWrapper.between("period_goods_time", strDate + " 00:00:00", strDate + " 23:59:59");
        Page<SyTimePeriodGoods> page = new Page<>(pageNum, pageSize);
        IPage iPage = iSyTimePeriodGoodsService.page(page, queryWrapper);
        List<SyTimePeriodGoods> syTimePeriodGoodsList = iPage.getRecords();
        //查询用户预约的商品
        //判断商品抢购状态
        /*if(CollectionUtils.isNotEmpty(syTimePeriodGoodsList) && hotCake == 1){
            SyTimePeriodGoods syTimePeriodGoods = syTimePeriodGoodsList.get(0);
            String periodTime = syTimePeriodGoods.getPeriodTime();
            String[] split = periodTime.split(":");
            int hours = new Date().getHours();
            if(hours < Integer.valueOf(split[0])){
                syTimePeriodGoodsList.removeAll(syTimePeriodGoodsList);
            }
        }*/
    /*    AppUser appUser = getAppUser();
        if (!StringUtils.isEmpty(appUser)) {
            QueryWrapper queryWrapper1 = new QueryWrapper();
            queryWrapper1.eq("user_id", appUser.getUserId());
            queryWrapper1.between("item_price_date", strDate + " 00:00:00", strDate + " 23:59:59");
            List<SyTimePeriodAppointment> syTimePeriodAppointmentList = iSyTimePeriodAppointmentService.list(queryWrapper1);
            if (CollectionUtils.isNotEmpty(syTimePeriodAppointmentList) && CollectionUtils.isNotEmpty(syTimePeriodGoodsList)) {
                for (SyTimePeriodGoods syTimePeriodGoods : syTimePeriodGoodsList) {
                    for (SyTimePeriodAppointment syTimePeriodAppointment : syTimePeriodAppointmentList) {
                        if(syTimePeriodGoods.getItemId().longValue() == syTimePeriodAppointment.getItemId().longValue()){
                            syTimePeriodGoods.setAppointment(1);
                            break;
                        }
                    }
                }
            }
        }
        Long userId = null;
        if(appUser != null){
            userId = appUser.getUserId();
        }
         iTaoBaoService.calculatedGoodsCommission(userId,syTimePeriodGoodsList);
        */
        return ServerResponse.createBySuccess("查询成功", iPage);
    }
}
